package com.jf.furn.web;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.jf.furn.bean.Furniture;
import com.jf.furn.bean.Message;
import com.jf.furn.service.FurnitureService;
import jakarta.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.Errors;
import org.springframework.validation.FieldError;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created with IntelliJ IDEA
 * Description:
 * User:22954
 * Date:2024-11-18
 * Time:10:48
 */
@RequestMapping("/furn")
@RestController
public class FurnitureController {
    @Autowired
    private FurnitureService furnitureService;

    @PostMapping("/save")
    public Message save(@Valid @RequestBody Furniture furniture, Errors errors) {
        if (errors.hasErrors()) {
            Map<String, String> errorMap = new HashMap<>();
            List<FieldError> fieldErrors = errors.getFieldErrors();
            for (FieldError fieldError : fieldErrors) {
                errorMap.put(fieldError.getField(), fieldError.getDefaultMessage());
            }
            Message message = Message.getFailed();
            message.addData("errorMsg", errorMap);
            return message;
        }
        furnitureService.save(furniture);
        return Message.getSuccess();
    }

    @GetMapping("/list")
    public Message listByPage(@RequestParam(value = "pageNum", defaultValue = "1") int pageNum,
                              @RequestParam(value = "pageSize", defaultValue = "5") int pageSize,
                              @RequestParam(value = "name", required = false) String name) {
        PageHelper.startPage(pageNum, pageSize);
        List<Furniture> pageFurniture = furnitureService.getFurnitureByName(name);
        PageInfo pageInfo = new PageInfo(pageFurniture);
        Message message = Message.getSuccess();
        message.addData("pageInfo", pageInfo);
        return message;
    }

    @PutMapping("/update")
    public Message update(@RequestBody Furniture furniture) {
        furnitureService.updateFurniture(furniture);
        return Message.getSuccess();
    }

    @DeleteMapping("/delete/{id}")
    public Message delete(@PathVariable(value = "id") int id) {
        furnitureService.deleteFurnitureById(id);
        return Message.getSuccess();
    }
}
